<template>
  <view class="file-dir-container" :style="listHeightStylePage">
    <up-navbar title="查看文件" @leftClick="fileDirClose" placeholder></up-navbar>
    <view style="padding-right: 20rpx;padding-left: 20rpx;padding-top: 20rpx;">
      <scroll-view :refresher-background="'transparent'" class="file-dir-list" :style="listHeightStyle" scroll-y="true"
        :refresher-enabled="true" :refresher-triggered="isRefreshing" @refresherrefresh="onRefresh"
        @scrolltolower="loadMore">
        <view v-for="(item, index) in searchResults" :key="index" class="file-dir-item">
          <!-- 头像和发送人 -->
          <view class="file-dir-header">
            <view class="file-dir-avatar">
              <image v-if="item.avatar" :src="item.avatar" class="avatar-circle"></image>
              <view v-else class="avatar-circle">{{ showUserName(item.username) }}</view>
            </view>
            <view class="file-dir-sender">
              <text class="sender-name">{{ item.username }}</text>
            </view>
            <view>
              <text style="font-size: 24rpx;color: #999;position: relative;top: -18rpx" class="sender-time">{{
                item.sendtime }}</text>
            </view>
          </view>

          <!-- 文件 -->
          <view class="file-dir-content">
            <view class="file-dir-info">
              <!-- 文件消息 -->
              <template v-if="item.type === 'file' || item.type === 'dir'">
                <view class="file-message" @click="openDoc(item)">
                  <view class="file-logo">
                    <image :src="`/static/fileType_big/${setFileIcon(item.name)}_b.png`" mode="widthFix"
                      style="width: 50rpx;"></image>
                  </view>
                  <view class="file-name">
                    <view>{{ truncateMiddle(item.name) }}</view>
                    <text>{{ item.formatSize }}</text>
                  </view>
                </view>
              </template>
            </view>
          </view>
        </view>

        <view v-if="searchResults.length === 0" class="no-file-dir">
          <text>暂无文件</text>
        </view>

        <!-- 加载中提示 -->
        <view v-if="loading" class="loading-text">
          加载中...
        </view>

        <!-- 没有更多数据提示 -->
        <view v-if="noMore" class="no-more-text">
          没有更多数据了
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import { chatApi } from '@/apis/cloud/chat';
import { useChatStore, useGroupStore, useUserStore } from '@/pinia-store/user';
import { fileTypeFormat } from "@/utils/chat";
import { mapStores } from 'pinia';
export default {
  name: "Groupchatfiles",
  data () {
    return {
      fileDirList: [],
      friend: null,
      imInfo: null,
      userInfo: null,
      dialogId: null,
      listHeight: 0, // 动态计算的高度
      listHeightStyle: {}, // 动态计算的样式
      topHeight: 0,
      listHeightStylePage: {},
      Chatarray: [],
      searchResults: [],
      isRefreshing: false,
      page: 1,
      loading: false,
      noMore: false,
      nextCloud: {}
    }
  },
  computed: {
    ...mapStores(useChatStore, useUserStore, useGroupStore),
  },
  onLoad () {
    this.imInfo = this.chatStore.imInfo;// 当前登录用户
    this.userInfo = this.userStore.user;
    this.infoId = this.chatStore.imInfo.id
    this.group = this.groupStore.group;
    this.Getxiaoxi()
  },
  created () {
    this.nextCloud = uni.getStorageSync('next_cloud');
    // #ifdef H5
    this.listHeightStylePage = {
      height: `${window.innerHeight}px`,
    };
    // #endif

    // #ifdef APP-PLUS
    const res = uni.getSystemInfoSync();
    this.listHeight = res.windowHeight;
    this.listHeightStylePage = {
      height: `${res.windowHeight}px`,
    };

    // #endif
    this.calculateListHeight()
  },
  methods: {
    truncateMiddle (text, maxLength = 20) {
      if (text.length <= maxLength) return text;
      const half = Math.floor(maxLength / 2.5);
      return `${text.slice(0, half)}...${text.slice(-half)}`;
    },
    openDoc (item2) {
      const type = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf'];
      const str = item2.name.split('.');
      const icon = str[str.length - 1];
      const that = this;
      let url = ''
      const xtoken = this.nextCloud.xtoken
      const fileName = encodeURIComponent(encodeURIComponent(item2.name)); // 双重编码
      const fileurl = encodeURIComponent(item2.url); // 单次编码
      if (type.indexOf(icon) != -1) {
        let previewUrl = ''
        if (xtoken) {
          previewUrl = `https://cloud.mfarmers.com/dist/previewDoc1.html?xtoken=${xtoken}&nc_id=${item2.nc_id ? item2.nc_id : ''}&fileName=${fileName}&type=mobile&user=${that.userStore.user.worker_id}&url=${fileurl}`
        } else {
          previewUrl = `https://cloud.mfarmers.com/dist/previewDoc1.html?fileName=${fileName}&type=mobile&user=${that.userStore.user.worker_id}&url=${fileurl}`
        }
        let encodedData = encodeURIComponent(JSON.stringify({ previewUrl }));
        url = `/pages/chat/message/common/previewDoc?data=${encodedData}`
      } else {
        url = `/pages/chat/message/common/downloadDoc?fileName=${fileName}&fileSize=${item2.formatSize}&url=${fileurl}`
      }

      uni.navigateTo({
        url: url
      })
    },
    // 文件图标处理
    setFileIcon (fileName) {
      const str = fileName.split('.');
      return fileTypeFormat(str[str.length - 1])
    },
    calculateListHeight () {
      const windowHeight = window.innerHeight; // 视口高度
      const topHeight = this.topHeight || 0; // 顶部安全高度
      const navbarHeight = 41; // 导航栏高度（假设为 44px）
      const tabsHeight = 20;
      // #ifdef APP-PLUS
      this.listHeightStyle = {
        overflowY: 'hidden',
        height: `${this.listHeight - 95}px`,
      };
      // #endif

      // #ifdef H5
      const listHeight = windowHeight - topHeight - navbarHeight - tabsHeight;
      this.listHeightStyle = {
        height: `${listHeight}px`,
        overflowY: 'hidden',

      };
      // #endif
    },
    fileDirClose () {
      uni.navigateBack();
    },
    processAllMessages () {
      return this.Chatarray.reduce((result, item) => {
        if (item.status == 12) {
          return result
        }

        try {
          const parsedContent = JSON.parse(item.content);
          if (!Array.isArray(parsedContent)) return result;

          const processedMessages = parsedContent.map(msg => {
            // 过滤掉空内容的消息
            if (!msg.content || (typeof msg.content === 'string' && !msg.content.trim())) {
              return null;
            }

            const baseData = {
              fromname: item.fromname,
              toname: item.to_name,
              sendtime: item.send_time,
              username: item.username,
              avatar: item.avatar
            };

            switch (msg.type) {
              case 'file':
                return {
                  ...baseData,
                  type: 'file',
                  name: msg.name,
                  url: msg.url,
                  formatSize: msg.formatSize,
                  rawContent: msg.content
                };

              default:
                return null;
            }
          }).filter(Boolean);

          return result.concat(processedMessages);
        } catch (e) {
          console.error('消息处理错误:', e, item);
          return result;
        }
      }, []);
    },
    async onRefresh () {
      this.isRefreshing = true; // 开始刷新
      this.Chatarray = [];
      this.page = 1;
      this.noMore = false;
      await this.Getxiaoxi();

    },
    async loadMore () {
      if (this.loading || this.noMore) return;
      this.page++;
      await this.Getxiaoxi();
    },
    // 获取消息记录
    async Getxiaoxi () {
      if (this.loading) {
        return
      }

      this.loading = true;
      uni.showLoading({
        title: '加载中....'
      });
      const params = {
        'data[groupId]': this.group.group_id,
        'data[account]': this.imInfo.account,
        'data[token]': this.userInfo.token,
        'data[myAccount]': this.imInfo.account,
        'data[page]': this.page,
        'data[pageSize]': 100,
        url: 'index.php/users/Group/getGroupChatRecord'
      }

      const msg = await chatApi(this.userInfo.token, params);

      if (msg.code == 200) {

        this.Chatarray = this.page == 1 ? msg.data.reverse() : [...this.Chatarray, ...msg.data.reverse()];

        if (msg.data.length == 0) {
          this.noMore = true;
        }
        this.isRefreshing = false;
        this.loading = false;
        uni.hideLoading();


        this.searchResults = this.processAllMessages();
      } else {
        this.loading = false;
        this.noMore = true;
        this.isRefreshing = false;
        uni.hideLoading();
      }
      uni.hideLoading();
    },
    // 名称超长处理
    showUserName (username) {
      if (username && username.length > 2) {
        return username.substr(1, 2);
      } else {
        return username;
      }
    },
  }

}
</script>



<style scoped lang="scss">
.loading-text,
.no-more-text {
  margin-top: 20rpx;
  text-align: center;
  padding: 20rpx;
  color: #999;
  font-size: 28rpx;
}

// 查看文件和链接
.file-dir-container {
  width: 100vw;
  background-color: #f3f3f3;
  overflow-y: hidden;

  .file-dir-list {

    height: 93vh;
    overflow-y: auto;

    .file-dir-item {
      background-color: #ffffff;
      border-radius: 20rpx;
      padding: 20rpx;
      margin-bottom: 20rpx;

      .file-dir-header {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;

        .file-dir-avatar {
          margin-right: 20rpx;

          .avatar-circle {
            width: 80rpx;
            height: 80rpx;
            border-radius: 15%;
            background-color: #377fff;
            color: #fff;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 32rpx;
            font-weight: bold;
          }
        }

        .file-dir-sender {
          flex: 1;
          display: flex;
          flex-direction: column;

          .sender-name {
            font-size: 28rpx;
            color: #333;
            font-weight: bold;
            margin-bottom: 30rpx;
          }

          .sender-time {
            font-size: 22rpx;
            color: #999;
          }
        }
      }

      .file-dir-content {
        display: flex;
        align-items: center;
        padding: 15rpx;
        background-color: #f8f8f8;
        border-radius: 10rpx;

        .file-dir-icon {
          width: 60rpx;
          height: 60rpx;
          margin-right: 20rpx;
        }

        .file-dir-info {
          flex: 1;
          display: flex;
          flex-direction: column;

          .file-dir-name {
            font-size: 28rpx;
            color: #333;
            margin-bottom: 5rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .file-dir-size {
            font-size: 24rpx;
            color: #999;
          }
        }

        .arrow-icon {
          margin-left: 10rpx;

          :deep(.u-icon__icon) {
            font-size: 24rpx;
            color: #999;
          }
        }
      }
    }

    .no-file-dir {
      text-align: center;
      padding: 40rpx 0;
      color: #999;
      font-size: 26rpx;
    }
  }
}

.file-message {
  display: flex;

  .file-logo {
    margin-right: 20rpx;
    // #ifdef H5
    margin-top: 20rpx;
    // #endif

    // #ifdef APP-PLUS
    margin-top: 5rpx;
    // #endif
  }
}
</style>
